<script lang='ts' setup>
import { onBeforeMount, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import request from "@/assets/工具/网络请求"
import { ID_REG, NAME_REG, PHONE_REG, SCHOOL } from '@/assets/工具/枚举';
import type { BookingFormData, VisitorInfo } from '@/types';
const router = useRouter()
const editActive = ref(false)   /*编辑状态 */
const currentShowVisitor = ref({} as VisitorInfo)   /* 当前用户选择的游客信息 */
const allVisitorInfo = ref([] as VisitorInfo[])  /* 数组：存放所有游客信息 */
const newVisitorInfo = reactive({} as VisitorInfo)   /* 新增的用户信息 */
const submitData: BookingFormData = {} as BookingFormData/* 提交并保存到数据库的预约信息 */
const pageBack = () => {
    router.push('/bookingVisitSchool')
}

onMounted(
    
    async () =>{
       
       
            const req = await request.doGet(`/insertUserInfoServlet?name=${sessionStorage.getItem('name')}`)
           
        currentShowVisitor.value = req.data
   
        allVisitorInfo.value[0] = req.data
        newVisitorInfo.name = req.data.name
       
        newVisitorInfo.phoneNumber = req.data.phoneNumber
        newVisitorInfo.idCode = req.data.idCode
        addVisitorInfo()
        
        
  
    }
)
const getFormatDay = (day: number, index: number): string | undefined => {
    switch (index) {
        case 0:
            return '今天'   /* return ：结束方法并返回后面的值 */
        case 1:
            return '明天'
    }
    switch (day) {
        case 1:
            return '周一'
        case 2:
            return '周二'
        case 3:
            return '周三'
        case 4:
            return '周四'
        case 5:
            return '周五'
        case 6:
            return '周六'
        case 0:
            return '周日'
    }
}
const selectDefaultDate = (index: number, date: Date) => {
    if ([3, 5, 6, 0].indexOf(date.getDay()) === -1) {
        /* 不可预约日期 */
        dateOptionClass[index] = '不可预约日期'
    }
    for (let className of dateOptionClass) {
        if (className === '已选择日期') return    /* 如果已经选中了一个，则结束方法 */
    }
    if ([3, 5, 6, 0].indexOf(date.getDay()) !== -1) {   /* 判断是否为可预约的日期 */
        dateOptionClass[index] = '已选择日期'
        submitData.visitDate = date   /* 预约进校的年月日时分秒（date对象） */
    }
}
const getFormatDate = (index: number) => {
    const date = new Date();
    date.setDate(date.getDate() + index)  /* 修改新创建的date对象的日期 */
    selectDefaultDate(index, date)
    return {
        day: getFormatDay(date.getDay(), index),
        date: `${date.getMonth() + 1}-${date.getDate()}`,
        originalDate: date,
        isAllow: [3, 5, 6, 0].indexOf(date.getDay()) !== -1 ? "<span style='color:green'>可预约</span>" : "不可预约"
    }
}

const dateOptionClass = reactive([
    '',
    '',
    '',
    ''
])
const UserStyle= reactive([
    '游客姓名1',
    '',
    '',
    ''
])
const selectDate = (dateObject: any, index: number) => {
    if (dateObject.isAllow !== "<span style='color:green'>可预约</span>") return
    for (let i in dateOptionClass) {
        dateOptionClass[i] = ''
    }
    dateOptionClass[index] = '已选择日期'
    submitData.visitDate = dateObject.originalDate   /* 预约进校的年月日时分秒（date对象） */
}


const getAllVisitorInfo = (visitor?: VisitorInfo) => {  /* 查询当前用户信息 */
    request.doGet(SCHOOL.VISITOR_INFOMATION).then(result => {
        if (result.status === 200) {
            
            allVisitorInfo.value = result.data    /* 将所有游客信息赋值给allVisitorInfo数组 */
            if (visitor) {
                currentShowVisitor.value = visitor   /* 新增后，默认显示此对象 */
            } else {
                currentShowVisitor.value = result.data[0]    /* 第一个游客的信息 */
            }
        }
    })
}
const addVisitorInfo = () => {  /* 发送post请求，新增游客信息 */
    if(!tip3.value &&!tip1.value && !tip2.value ){
        newVisitorInfo.userId = parseInt(sessionStorage.getItem('token')!,10);
    request.doPost(SCHOOL.VISITOR_INFOMATION, newVisitorInfo).then(result => {
        if (result.status === 201) {  /* 新增游客信息成功，将对象属性值初始化，然后将文本框隐藏 */
            newVisitorInfo.idCode = ''
            newVisitorInfo.name = ''
            newVisitorInfo.phoneNumber = ''
            editActive.value = false
            getAllVisitorInfo(result.data)
        }
    }).catch(err => {
        console.log(err);
    })
    }
  
}
const deleteVisitor = (id: number) => {   /* 发送delete请求，根据id删除指定的用户信息 */
    if (allVisitorInfo.value.length === 1) return
    request.doDelete(SCHOOL.VISITOR_INFOMATION + "/" + id).then(res => {
        if (res.status === 200) {
            getAllVisitorInfo()  /* 删除成功后，再次查询第一个用户的信息 */
        }
    })
}
const switchVisitor = (i: number) => {   /* 将当前选择的游客信息保存到currentShowVisitor对象中 */
    
    currentShowVisitor.value = allVisitorInfo.value[i]
    changeStyle(i)
}
 
const submitOrder = () => {
   
    submitData.bookingTime = new Date()
    currentShowVisitor.value.userId = parseInt(sessionStorage.getItem('token')!,10);
    submitData.visitorsInfo = allVisitorInfo.value
    request.doPost(SCHOOL.BOOKING_ORDER, submitData).then(res => {
        if (res.status === 200) router.push('/bookingVisitSchoolList')
    })
}
getAllVisitorInfo()  /* 调用‘查询当前用户信息’方法 */
const tip1 = ref('')
const tip2 = ref('')
const tip3 = ref('')
/* 
    手机号加密方法如下：
    '18008610290'.substr(0,3)+'****'+'18008610290'.substr(7)
*/
const verifyName = () => {   /* 文本框失去焦点时校验一次，另外提交保存时所有的内容还要再校验一次。 */
    if (newVisitorInfo.name.trim() == '') {
        tip1.value = '姓名不可为空'
    } else if (NAME_REG.test(newVisitorInfo.name.trim())) {
        tip1.value = ''
    } else {
        tip1.value = '姓名格式错误'
    }
}


const changeStyle = (index:number)  =>{
    
    for (let i= 0; i < 4;i++ ){
        UserStyle[i] = ''
    }
    UserStyle[index]='游客姓名1'
}

// onBeforeMount(
//     async() =>{
//         const id = sessionStorage.getItem('token')
//         const date = await request.doGet(`/UpUserInfoServlet?id=${id}`)
//         allVisitorInfo.value = date.data
//         console.log(allVisitorInfo);
        
        
//     }
// )

const verifyID = async () => {
    if (!newVisitorInfo.idCode || newVisitorInfo.idCode.trim() === '') {
        tip2.value = '身份证号不可为空'
    } else if (ID_REG.test(newVisitorInfo.idCode.trim())) {
        // const res = await request.doGet(SCHOOL.VISITOR_INFOMATION, {
        //     params: {
        //         idCode: newVisitorInfo.idCode.trim()
        //     }
        // })
        // if (res.data.length > 0) {
        //     tip2.value = '身份证号已存在'
        // } else {
        //     tip2.value = ''
        // }
tip2.value = ''
    } else {
        tip2.value = '身份证号格式错误'
    }
}

const phone = () =>{
    if (!newVisitorInfo.phoneNumber || newVisitorInfo.phoneNumber.trim() === '') {
        tip3.value = '电话号码号不可为空'
    } else if (PHONE_REG.test(newVisitorInfo.phoneNumber.trim())) {
   
 tip3.value = ''
    } else {
        tip3.value = '电话号码格式错误'
    }
}

</script>
<template>
    <div class="组件根标签">
        <div class="标题栏">
            <div class="标题栏占位" @click="pageBack">
                <img src="@/assets/图片/通用/白色返回箭头.png" class="返回箭头 块级图片">

            </div>
            预约信息
            <div class="标题栏占位">
            </div>
        </div>
        <div id="预约信息">
            <div id="校园名称">
                黄冈科技职业学院
            </div>
            <div class="选项卡标题">
                选择日期
            </div>
            <ul id="日期列表">
                <li v-for="(e, i) in 4" @click="selectDate(getFormatDate(i), i)" :class="dateOptionClass[i]">
                    <div>
                        {{ getFormatDate(i).day }}&nbsp;{{ getFormatDate(i).date }}
                    </div>
                    <div v-html="getFormatDate(i).isAllow">
                    </div>
                </li>
            </ul>
        </div>

        <div id="游客信息">
            <div class="选项卡标题">
                游客信息
            </div>
            <div id="游客选择">
                <div v-for="(visitor, i) of allVisitorInfo" :key="visitor.id" @click="switchVisitor(i)" class="游客姓名" :class="UserStyle[i]">
                    {{ visitor.name }}
                </div>
                <div @click="editActive = true" v-if="allVisitorInfo.length <= 3 && editActive === false" id="新增按钮">
                    新增+
                </div>
            </div>
            <div class="IdStyle" >
                <span class="游客信息字段名">
                    姓名
                </span>
                <template v-if="editActive">
                    <input v-model="newVisitorInfo.name" @blur="verifyName"><span class="错误提示">{{ tip1 }}</span>
                </template>
                <span class="IdStyleSpan" v-else>{{ currentShowVisitor.name }}</span>
            </div>
            <div class="IdStyle">
                <span class="游客信息字段名">身份证</span>

                <template v-if="editActive">
                    <input v-model="newVisitorInfo.idCode" @blur="verifyID"><span class="错误提示">{{ tip2 }}</span>
                </template>
                <span class="IdStyleSpan" v-else>{{ currentShowVisitor.idCode }}</span>
                
            </div>
            <div class="IdStyle">
                <span class="游客信息字段名">手机号</span>

                <template v-if="editActive">
                    <input @blur="phone" v-model="newVisitorInfo.phoneNumber"><span class="错误提示">{{ tip3 }}</span>
                </template>
                <span class="IdStyleSpan" v-else>{{
                    currentShowVisitor.phoneNumber
                    }}</span>
            </div>
            <img v-if="!editActive && allVisitorInfo.length > 1"
                 src="@/assets/图片/通用/删除.png" id="删除图标" @click="deleteVisitor(currentShowVisitor.id)">
            <template v-if="editActive">
                <div class="addCancle">
                    <button class="newAddText" @click="addVisitorInfo">保存</button>
                    <button class="cancel" @click="editActive = false">取消</button>
                </div>
                
            </template>
            <p>
                <button id="buttonSubmit" @click="submitOrder">立即提交</button>
            </p>
        </div>
    </div>
</template>
<style scoped>
/* :deep(button){

} */
.IdStyle span{
    margin-bottom: 4px;
}
.IdStyle span:nth-child(1){
    margin-top: 0px;
}
.IdStyleSpan{
    letter-spacing: 1px;
}
.IdStyle div,button,p{
    line-height: 25px;
}
.IdStyle button{
    margin-top: 10px;
}
.IdStyle{
    font-size: 14px;

}
.IdStyle input {
    border: none;
    outline: none;
    letter-spacing: 3px;
    width: 170px;
    border-bottom: 0.02667rem dashed #f1a145;
}
.addCancle{
    margin-top: 20px;
    display: flex;
    justify-content: space-around;
    
}
@font-face {
    font-family:kj;
    src: url("@/assets/字体/英雄提.ttf");
}
#buttonSubmit{
    width: 300px;
    position: fixed;
    font-family: kj;
    left:calc(50% - 150px);
    bottom: 300px;
    letter-spacing: 10px;
    height: 44px;
    color: #fff;
    font-size: 30px;
    border-radius: 25px;
    background: rgba(120, 78, 35, 1);
}
.cancel{
    background-color: aliceblue;
    width: 100px;
    border: #f1a145 1px solid;
    display: block;
   
    color: #686868;
    border-radius: 6px;
    text-align: center;
    height: 30px;
}
.newAddText{
    background-color: aliceblue;
    color: #686868;
    border: #f1a145 1px solid;
    border-radius: 5px;
    letter-spacing: 6px;
    text-align: center;
    width: 100px;
    height: 30px;
}
input{
    border: none;
    outline: none;
    border-bottom: 1px solid #783c14;
    width: 130px;
}
#删除图标{
    width: 25px;
    height: 25px;
    position: absolute;
    right: 30px;
    top:120px;
}
.游客信息行{
    margin-bottom: 3px;
}
.游客信息字段名{
    width: 60px;
    display: inline-block;
}
#游客选择 {
    display: flex;
    position: relative;
    margin: 12px 0 20px;
}

#新增按钮 {
    width: 71px;
    height: 21px;
    border-radius: 3px;
    background: rgba(120, 78, 35, 1);
    border: 1px solid rgba(194, 194, 194, 1);
    color: #FFF;
    line-height: 21px;
    text-align: center;
    font-size: 12px;
    position: absolute;
    right: 0;
}
.游客姓名1 {
    width: 71px;
    height: 21px;
    border-radius: 3px;
    border: 1px solid rgb(184, 116, 47) !important;
    background-color: #f4e8d1;
    font-size: 12px;
    line-height: 21px;
    text-align: center;
    color: rgba(120, 78, 35, 1);
    margin-right: 9px;
}

.游客姓名 {
    width: 71px;
    height: 21px;
    border-radius: 3px;
    /* background: rgba(240, 223, 199, 1); */
    border: 1px solid rgba(248, 240, 229, 1);
    font-size: 12px;
    line-height: 21px;
    text-align: center;
    color: rgba(120, 78, 35, 1);
    margin-right: 9px;
}

#游客信息 {
    width: 342px;
    height: 220px;
    background: #FFF;
    margin: 11px auto 0;
    padding: 16px 8px;
    box-sizing: border-box;
    border-radius: 5px;
    position: relative;
}

.错误提示 {
    color: red;
}

.不可预约日期 {
    background-color: #e1e0e0;
    color: #6e6c6c;
}

.已选择日期 {
    border: 1px solid rgb(184, 116, 47) !important;
    background-color: #f4e8d1;
}

#日期列表 li {
    width: 76px;
    height: 46px;
    border-radius: 5px;
    border: 1px solid rgba(194, 194, 194, 1);
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    padding: 5px 0;
    box-sizing: border-box;
}

.选项卡标题 {
    color: rgba(17, 34, 51, 1);
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 12px;
}

#校园名称 {
    color: rgba(85, 85, 85, 1);
    font-size: 18px;
    line-height: 50px;
}

#日期列表 {
    display: flex;
    font-size: 12px;
    text-align: center;
    justify-content: space-between;
}

#预约信息 {
    width: 342px;
    height: 152px;
    background: #FFF;
    margin: auto;
    padding: 0 8px;
    box-sizing: border-box;
}

.组件根标签 {
    background: linear-gradient(0deg, rgba(145, 74, 3, 0) 0%, rgb(130, 88, 46) 80%, rgba(120, 78, 35, 1) 100%);
    font-size: 14px;
    height: 454px;
}

.标题栏占位 {
    width: 40px;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.标题栏 {
    display: flex;
    font-size: 17px;
    align-items: center;
    height: 44px;
    justify-content: space-between;
    box-sizing: border-box;
    width: 375px;
    color: #FFF;
}

.返回箭头 {
    width: 9px;
    height: 18px;
}
</style>